package com.promise.jokerdream.work.signin.newact

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 神魔转盘工作
class SaviorsTurntableWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "神魔转盘"

    override val priority: Int
        get() = 8

    override val isActWork: Boolean
        get() = true

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 先查询神魔转盘信息，检查是否有免费次数
            val queryResult = gameApi.querySaviorsTurntable()
            queryResult.fold(
                onSuccess = { response ->
                    // 检查是否有免费次数 (freeTimes > 0 表示有免费次数)
                    if (response.freeTimes > 0) {
                        // 2. 有免费次数，进行抽奖
                        val claimResult = gameApi.claimSaviorsTurntable()
                        claimResult.fold(
                            onSuccess = { claimResponse ->
                                historyManager.addHistory(name, claimResponse.getDescription())
                                WorkResult.Success
                            },
                            onFailure = { exception ->
                                historyManager.addHistory(name, exception.message)
                                WorkResult.Failure(exception, exception.message)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                    WorkResult.Failure(exception, exception.message)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}